package reporting

import (
	"fmt"
	"gitee.com/mootok/mootok/src/constant/config"
	"gitee.com/mootok/mootok/src/constant/strings"
	"gitee.com/mootok/mootok/src/models"
	"gitee.com/mootok/mootok/src/services/user"
	"gitee.com/mootok/mootok/src/services/video"
	"gitee.com/mootok/mootok/src/storage/clickhouse"
	"gitee.com/mootok/mootok/src/storage/redis"
	"gitee.com/mootok/mootok/src/utils/logging"
	"gitee.com/mootok/mootok/src/web/api"
	"gitee.com/mootok/mootok/src/web/common/response"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis_rate/v10"
	"github.com/sirupsen/logrus"
	"net/http"
)

type ApiReportingImpl struct{}

var reportVideoPlayLimitKeyPrefix = config.EnvConfig.RedisPrefix + "report_video_play_freq_limit"
var reportVideoShareLimitKeyPrefix = config.EnvConfig.RedisPrefix + "report_video_share_freq_limit"
var reportVideoShareClickLimitKeyPrefix = config.EnvConfig.RedisPrefix + "report_video_share_click_freq_limit"
var videoPlayMaxQPM = 10

var VideoService video.Service
var UserService user.Service

func genReportVideoPlayLimiterKey(userID int) string {
	return fmt.Sprintf("%s-%d", reportVideoPlayLimitKeyPrefix, userID)
}

func (*ApiReportingImpl) ReportVideoPlay(c *gin.Context) {
	var err error
	var req api.ReportVideoPlayReq
	ctxUserId, _ := c.Get(strings.UserLoginContext)
	userId := ctxUserId.(int)

	err = c.BindJSON(&req)
	if err != nil {
		response.FailWithMsg(c, http.StatusBadRequest, strings.ParamsErrorCode, strings.ParamsError)
		return
	}

	logger := logging.LogService("Reporting.VideoPlay").WithFields(logrus.Fields{
		"user_id":  userId,
		"video_id": req.VideoId,
		"progress": req.Progress,
	})

	// Rate limit
	limiter := redis_rate.NewLimiter(redis.Client)
	limiterKey := genReportVideoPlayLimiterKey(userId)
	limiterRes, err := limiter.Allow(c, limiterKey, redis_rate.PerSecond(videoPlayMaxQPM))
	if err != nil {
		response.FailWithMsg(c, http.StatusInternalServerError, strings.RedisOperationErrorCode, strings.InternalServiceError)
		logger.Errorf("limiter.Allow: %s", err.Error())
		return
	}
	if limiterRes.Allowed == 0 {
		logger.Errorf("ratelimit hit.")
		response.FailWithMsg(c, http.StatusInternalServerError, strings.RateLimitHitErrorCode, strings.RateLimitHit)
		return
	}

	published, err := VideoService.IsPublished(req.VideoId)
	if err != nil {
		logger.Errorf("failed query video existence: %v", err)
		response.FailWithMsg(c, http.StatusInternalServerError, strings.DataBaseSelectErrorCode, strings.InternalServiceError)
		return
	}
	if !published {
		logger.Infof("video record not found: %v", err)
		response.FailWithMsg(c, http.StatusNotFound, strings.NotFoundErrorCode, strings.NotFoundError)
		return
	}
	if err = clickhouse.Client.Create(&models.ReportedVideoPlay{
		VideoId:  int32(req.VideoId),
		Progress: req.Progress,
		UserId:   int32(userId),
	}).Error; err != nil {
		logger.Errorf("failed save post video to db: %v", err)
		response.FailWithMsg(c, http.StatusInternalServerError, strings.DataBaseInsertErrorCode, strings.InternalServiceError)
		return
	}
	response.Success(c, strings.SuccessCode)
	logger.Info("report saved.")
}
